package com.zjhome.cloudnote.controller;

import java.util.List;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.zjhome.cloudnote.domain.NoteInfo;
import com.zjhome.cloudnote.param.AckResult;
import com.zjhome.cloudnote.service.NoteService;
import com.zjhome.cloudnote.service.UserService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 分享接口
 * 
 * @author zjhome
 *
 */
@Controller	// 使用 themeleaf 渲染，这里不能使用 RestController
@RequestMapping("/share")
@Api(value = "分享")
public class ShareController extends BaseController {
	@Autowired
	private UserService		userService;
	
	@Autowired
	private NoteService 	noteService;
	
	@GetMapping("/view/{id}")
	@ApiOperation(value = "查看分享的笔记")
	public String shareView(HttpServletRequest request, @PathVariable("id") String id) throws Exception {

		NoteInfo noteInfo = noteService.selectShareNote(id);
		
		if (noteInfo == null) {
			// 未找到有效的分享笔记			
			request.setAttribute("title", "不是有效的url或用户已停止分享!");
			request.setAttribute("content", "");
		}
		else {
			// 找到有效的分享笔记
			request.setAttribute("title", noteInfo.getTitle());
			request.setAttribute("content", noteInfo.getContent());
		}		
		
		return "sharenote";
	}

	
	/**
	 * 获取所有分享列表
	 * 
	 * @return	
	 * @throws Exception
	 */
	@PostMapping("/list")
	@ApiOperation(value = "分享列表")
	@ResponseBody
	public List<NoteInfo> shareList() throws Exception {
		
		NoteInfo noteInfo = new NoteInfo();
		
		noteInfo.setUid(this.getUserId());		
		return noteService.selectShareNotes(noteInfo);		
	}
	
	/**
	 * 分享笔记
	 * 
	 * @param id	笔记id
	 * @return
	 * @throws Exception
	 */
	@PostMapping("/openshare")
	@ApiOperation(value = "添加分享")
	@ResponseBody
	public NoteInfo openShare(@RequestParam("id") String id) throws Exception {
		
		NoteInfo noteInfo = noteService.setNoteShareConfig(id, this.getUserId(), 1);	// 开启分享
		return noteInfo;
	}
	
	/**
	 * 取消分享
	 * 
	 * @param id	笔记id
	 * @return
	 * @throws Exception
	 */
	@PostMapping("/cancelshare")
	@ApiOperation(value = "取消分享")
	@ResponseBody
	public NoteInfo cancelShare(@RequestParam("id") String id) throws Exception {
		NoteInfo noteInfo = noteService.setNoteShareConfig(id, this.getUserId(), 0);	// 关闭分享
		return noteInfo;
	}
	
}
